<?php
/**
 * @link https://ym2.cleverstone.top
 * @copyright Copyright (c) 2020 Yii Manager Software LLC
 */

namespace frontend\v1\behaviors;

use yii\filters\auth\HttpHeaderAuth;
use yii\web\Response;

/**
 * The default implementation of HttpHeaderAuth uses the [[\yii\web\User::loginByAccessToken()|loginByAccessToken()]] method of the user application component and passes the value of the X-Api-Key header.
 * This implementation is used for authenticating API clients.
 */
class HttpHeaderAuthX extends HttpHeaderAuth
{
    /**
     * {@inheritdoc}
     */
    public function authenticate($user, $request, $response)
    {
        $authHeader = $request->getHeaders()->get($this->header);

        if ($authHeader !== null) {
            if ($this->pattern !== null) {
                if (preg_match($this->pattern, $authHeader, $matches)) {
                    $authHeader = $matches[1];
                } else {
                    return null;
                }
            }

            try {
                return $user->loginByAccessToken($authHeader, get_class($this));
            } catch (\Exception $e) {
                $response->format = Response::FORMAT_JSON;
                $response->data = [
                    'code' => 500,
                    'msg' => $e->getMessage(),
                ];
            }
        }

        return null;
    }

    /**
     * {@inheritdoc}
     */
    public function handleFailure($response)
    {
        if (!empty($response->data)) {
            return;
        }

        $response->format = Response::FORMAT_JSON;
        $response->data = [
            'code' => 401,
            'msg' => 'Your request was made with invalid credentials.',
        ];
    }
}